package com.magnificent.atlantis.server.ui.panels.user;

import com.magnificent.atlantis.common.entity.ServerUser;
import com.magnificent.atlantis.common.user.ServerDescriptor;
import com.magnificent.atlantis.server.database.AtlantisDataSource;
import com.magnificent.atlantis.server.resources.AtlantisServerResources;
import com.magnificent.atlantis.server.settings.SettingsStorage;
import com.magnificent.atlantis.server.ui.MainFrame;
import com.magnificent.atlantis.server.ui.panels.common.AbstractServerPanel;
import com.magnificent.atlantis.server.ui.panels.user.dialog.UserDialog;
import com.magnificent.atlantis.server.ui.panels.user.table.UserTable;
import com.magnificent.atlantis.server.ui.panels.user.table.UserTableModel;
import com.magnificent.commons.ui.button.ButtonFactory;
import com.magnificent.commons.ui.dialogs.DialogConnector;
import com.magnificent.commons.ui.dialogs.DialogFactory;
import com.magnificent.commons.utils.collections.CollectionsUtils;
import com.magnificent.helpers.CommonUIHelper;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.File;

/**
 * ServerUser: Babanin
 * Date: 25.03.2009
 * Time: 20:00:56
 */
public class UserPanel extends AbstractServerPanel {

    private JButton addBtn;
    private JButton editBtn;
    private JButton deleteBtn;
    private JButton banBtn;

    private JButton exportUsersBtn;

    private UserTable userTable;
    private ServerUser selectedUser;

    public UserPanel() {
        initialize();
        initializeControls();
        initializeView();
    }

    private void initialize() {
        setLayout(new BorderLayout());
        setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    }

    private void initializeControls() {
        addBtn = ButtonFactory.button(AtlantisServerResources.ADD_USER, "New user", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                UserDialog.createUser(new DialogConnector<ServerUser>() {
                    public void objectSelected(ServerUser obj) {
                        AtlantisDataSource.getInstance().persist(obj);
                    }
                });
            }
        });

        banBtn = new JButton(new AbstractAction("", AtlantisServerResources.BAN_USER) {
            public void actionPerformed(ActionEvent e) {
                selectedUser.setBaned(!selectedUser.isBaned());
                AtlantisDataSource.getInstance().update(selectedUser);
            }
        });

        editBtn = ButtonFactory.button(AtlantisServerResources.EDIT_USER, "Edit user", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                UserDialog.editUser(selectedUser, new DialogConnector<ServerUser>() {
                    public void objectSelected(ServerUser obj) {
                        AtlantisDataSource.getInstance().update(selectedUser);
                    }
                });
            }
        });

        deleteBtn = ButtonFactory.button(AtlantisServerResources.DELETE_USER, "Delete user", new AbstractAction() {
            public void actionPerformed(ActionEvent e) {
                AtlantisDataSource.getInstance().delete(selectedUser);
                updatePanelButtons(null);
            }
        });

        userTable = new UserTable(new UserTableModel());
        userTable.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
            public void valueChanged(ListSelectionEvent e) {
                selectedUser = null;
                int row = userTable.getSelectedRow();

                if (row >= 0) {
                    selectedUser = userTable.getModel().getValue(row);
                }

                updatePanelButtons(selectedUser);
            }
        });

        exportUsersBtn = new JButton(new AbstractAction("", AtlantisServerResources.EXPORT_USERS) {
            public void actionPerformed(ActionEvent e) {
                DialogFactory.fileChooser(
                        new File(System.getProperty("user.dir")),
                        new FileNameExtensionFilter("Atlantis Service Descriptor (*.asd)", "asd"),
                        false,
                        MainFrame.findMainFrame(), new AbstractAction() {
                            public void actionPerformed(ActionEvent e) {
                                ServerDescriptor serverDescriptor = new ServerDescriptor();

                                serverDescriptor.setHost(SettingsStorage.getSettings().getHost());
                                serverDescriptor.setPort(SettingsStorage.getSettings().getPort());

                                serverDescriptor.setUserList(AtlantisDataSource.getInstance().getBeans(ServerUser.class));

                                String path = e.getActionCommand();
                                if (!path.endsWith(".asd")) {
                                    path = path + ".asd";
                                }

                                ServerDescriptor.save(path, serverDescriptor);
                            }
                        }, null, null);
            }
        });

        updatePanelButtons(null);
    }

    private void updatePanelButtons(ServerUser selectedUser) {
        boolean enabled = selectedUser != null;

        editBtn.setEnabled(enabled);
        deleteBtn.setEnabled(enabled);
        banBtn.setEnabled(enabled);

        if (enabled) {
            if (selectedUser.isBaned()) {
                banBtn.setIcon(AtlantisServerResources.UNBAN_USER);
                banBtn.setToolTipText("Unban user");
            } else {
                banBtn.setIcon(AtlantisServerResources.BAN_USER);
                banBtn.setToolTipText("Ban user");
            }
        }
    }

    private void initializeView() {
        add(
                CommonUIHelper.createVerticalBox(CommonUIHelper.createBorderLayoutPanel(
                        CollectionsUtils.array(banBtn, CommonUIHelper.createHorizontalBox(addBtn, 2, editBtn, 2, deleteBtn, 20, exportUsersBtn, 5)), CollectionsUtils.array(BorderLayout.LINE_START, BorderLayout.LINE_END)
                ), 5), BorderLayout.NORTH
        );

        add(new JScrollPane(userTable), BorderLayout.CENTER);
    }
}
